import { useCallback, useEffect, useRef, useState } from 'react';
import { useRecoilValue } from 'recoil';
import { getConversationList } from '../../../../api/conversation';
import { ConversationList } from '../../../../common/components/ConversationList';
import { ConversationWindows } from '../../../../common/components/ConversationWindows';
import { ConversationInfoItem, PermissionType } from '../../../../common/types/conversation';
import { useManagerIm } from '../../../../hooks/useManagerIm';
import { useRefCallback } from '../../../../hooks/useRefCallback';
import { userInfoState } from '../../../../store/userInfo';

import './index.css';

interface AllConversationProps {
  currentConversation?: ConversationInfoItem;
  handleChangeConversation: (conversation: ConversationInfoItem) => void;
}

export const AllConversation: React.FC<AllConversationProps> = (props) => {

  const { currentConversation, handleChangeConversation } = props;

  const [conversationInfo, setConversationInfo] = useState<Array<ConversationInfoItem>>([]);
  const conversationRef = useRef<any>(currentConversation);
  const managerIm = useManagerIm();
  const userInfo = useRecoilValue(userInfoState);


  const initConversationInfo = useCallback(async (conversation?: ConversationInfoItem) => {
    const result = await getConversationList();
    const { data } = result;
    const { conversation_list } = data;
    conversation_list && setConversationInfo(conversation_list);
    conversation_list && handleChangeConversation(conversation || currentConversation || conversation_list[0]);
  }, [currentConversation]);


  useEffect(() => {
    initConversationInfo();
  }, [localStorage.getItem('token')]);

  useEffect(() => {
    conversationRef.current = currentConversation;
  }, [currentConversation])


  useEffect(() => {
    if(userInfo.id) {
      managerIm.on('manager',async (data: { type: number; }) => {
        if(data.type === 1) { // 有新的工单来了，需要更新列表
          if(!(userInfo.permission === PermissionType.customer)) {
            await initConversationInfo(conversationRef.current);
          }
        }
      })
  
      managerIm.on(`manager_${userInfo.id}`, async (data: any) => {
        const { type, conversation } = data;
        if (type === 2) {
          await initConversationInfo(conversation);
        }
      })
    }
    
  }, [userInfo]);

  return (<div className='all-conversation-wrapper'>
    {currentConversation ? <>
      <div className='all-conversation-sider'>
        <ConversationList
          currentConversation={currentConversation}
          handleChangeConversation={handleChangeConversation}
          data={conversationInfo} />
      </div>
      <div className='all-conversation-content'><ConversationWindows initConversationInfo={initConversationInfo} currentConversation={currentConversation} /></div>
    </> : null}
  </div>)
}